package com.tma.demo.custom;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.util.Log;

import com.tma.demo.CustomListViewActivity;
import com.tma.demo.R;
import com.tma.demo.xml.Book;
import com.tma.demo.xml.BookParser;

public class LoadBookTask extends AsyncTask<Void, Void, LoadBookResult>
        implements OnCancelListener {

    private static final String TAG = "LoadBookTask";
    private ProgressDialog mProgressDialog;
    private WeakReference<CustomListViewActivity> mActivityRef;

    public LoadBookTask(CustomListViewActivity activity) {
        mActivityRef = new WeakReference<CustomListViewActivity>(activity);
    }

    @Override
    protected void onPreExecute() {
        mProgressDialog = buildProgressDialog();
        mProgressDialog.show();
    }

    @Override
    protected LoadBookResult doInBackground(Void... params) {
        BookParser parser = new BookParser();
        List<Book> books = null;
        Activity activity = mActivityRef.get();
        try {
            InputStream stream = activity.getResources().openRawResource(R.raw.book);
            books = parser.parse(stream);
        } catch (XmlPullParserException e) {
            Log.e(TAG, e.getMessage(), e);
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
        }
        return new LoadBookResult(books);
    }

    @Override
    protected void onPostExecute(LoadBookResult result) {
        hideProgressDialog();
        CustomListViewActivity activity = mActivityRef.get();
        if (activity != null) {
            List<Book> books = result.getBooks();
            activity.displayBooks(books);
        }
    }

    // progress dialog's cancel callback
    public void onCancel(DialogInterface dialog) {
        cancel(true);
    }

    public void attach(CustomListViewActivity activity) {
        mActivityRef.clear();
        mActivityRef = new WeakReference<CustomListViewActivity>(activity);
    }

    public void hideProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    public void resumeProgressDialog() {
        CustomListViewActivity activity = mActivityRef.get();
        if (getStatus() != Status.FINISHED && activity != null) {
            mProgressDialog = buildProgressDialog();
            mProgressDialog.show();
        }
    }

    private ProgressDialog buildProgressDialog() {
        ProgressDialog pd = new ProgressDialog(mActivityRef.get());
        pd.setTitle("Please wait");
        pd.setMessage("Processing...");
        pd.setCancelable(true);
        pd.setOnCancelListener(this);
        return pd;
    }
}
